<?php

class  AliSMS{

    protected $accessKeyId = 'LTAIvWCp8UFOhFOz';
    protected $accessKeySecret = 'vWcjMSvhsqa0Gyn9jEBlyRpLjb3oLY';

    public function send_sms($phone, $sms_param, $tpl = '', $security = false)
    {
        $params = [
            'PhoneNumbers' => $phone,
            'SignName' => '耀运动',
            'TemplateCode' => $tpl,
            'TemplateParam' => $sms_param,
            "RegionId" => "cn-hangzhou",
            "Action" => "SendSms",
            "Version" => "2017-05-25"
        ];
        $apiParams = $this->ali_createStrParam($params);
        $sortedQueryStringTmp = $this->ali_createSign($apiParams);
        $stringToSign = "GET&%2F&" . $this->encode(substr($sortedQueryStringTmp, 1));

        $sign = base64_encode(hash_hmac("sha1", $stringToSign, $this->accessKeySecret . "&", true));

        $signature = $this->encode($sign);
        $url = ($security ? 'https' : 'http') . "://dysmsapi.aliyuncs.com/?Signature={$signature}{$sortedQueryStringTmp}";

        try {
            $content = curl($url);
            $res = json_decode($content, true);
            if ($res['Code'] == 'OK') {
                return true;
            }
            loger(json_encode($res, JSON_UNESCAPED_UNICODE), 'sms');
            return false;

        } catch (\Exception $e) {
            loger($e->getMessage(), 'sms');
            return false;
        }
    }

    protected function ali_createStrParam($params)
    {
        $apiParams = array_merge(array(
            "SignatureMethod" => "HMAC-SHA1",
            "SignatureNonce" => uniqid(mt_rand(0, 0xffff), true),
            "SignatureVersion" => "1.0",
            "AccessKeyId" => $this->accessKeyId,
            "Timestamp" => gmdate("Y-m-d\TH:i:s\Z"),
            "Format" => "JSON",
        ), $params);
        ksort($apiParams);
        return $apiParams;
    }

    protected function ali_createSign($apiParams)
    {
        $sortedQueryStringTmp = "";
        foreach ($apiParams as $key => $value) {
            $sortedQueryStringTmp .= "&" . $this->encode($key) . "=" . $this->encode($value);
        }
        return $sortedQueryStringTmp;
    }

    protected function encode($str)
    {
        $res = urlencode($str);
        $res = preg_replace("/\+/", "%20", $res);
        $res = preg_replace("/\*/", "%2A", $res);
        $res = preg_replace("/%7E/", "~", $res);
        return $res;
    }


}
